package com.atguigu.gmall.order.controller;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.order.service.OrderInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @Author: lx
 * @Time: 11:41
 * @Description:
 */
@RestController
@RequestMapping("/api/order")
public class OrderApiController {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private OrderInfoService orderInfoService;
    //获取交易号
    @GetMapping("/auth/getTradeNo")
    public String getTradeNo(HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        //时间戳
        //long l = System.currentTimeMillis() + userId;  雪花算法
        //UUID
        String tradeNo = UUID.randomUUID().toString().replaceAll("-", "");
        redisTemplate.opsForValue().set("tradeNo:" + userId,tradeNo);
        return tradeNo;
    }

    //提交订单
    @PostMapping("/auth/submitOrder")
    public Result submitOrder(@RequestBody OrderInfo orderInfo,String tradeNo
    ,HttpServletRequest request){
        //1:校验交易号  幂等性问题
        String userId = AuthContextHolder.getUserId(request);
        String redisTradeNo = (String) redisTemplate.opsForValue().get("tradeNo:" + userId);
        if(StringUtils.isEmpty(redisTradeNo)){
            return Result.fail().message("请不要重复提交!");
        }else{
            if(!redisTradeNo.equals(tradeNo)){
                return Result.fail().message("请正确操作!");
            }
        }
        //删除
        redisTemplate.delete("tradeNo:" + userId);
        //判断是否还库存   有货或是无货
        //无货： 剩余数量小于购买数量
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        for (OrderDetail orderDetail : orderDetailList) {
            boolean isHasStock = orderInfoService.hasStock(orderDetail);
            if(!isHasStock){
                //无货
                return Result.fail().message(orderDetail.getSkuName() + ":无货");
            }
        }
        //提交订单
        orderInfo.setUserId(Long.parseLong(userId));
        Long orderId = orderInfoService.saveOrderInfo(orderInfo);
        return Result.ok(orderId);
    }

    //查询订单信息
    @GetMapping("/auth/getOrderInfo/{orderId}")
    public OrderInfo getOrderInfo(@PathVariable Long orderId){
        return orderInfoService.getOrderInfo(orderId);
    }
    //由库存系统发起申请  折单接口
    // http://order.gmall.com/api/order/orderSplit?orderId=xxx&wareSkuMap=xxx
    @PostMapping("/orderSplit")
    public List<Map> orderSplit(Long orderId,String wareSkuMap){
        //wareSkuMap  [{"wareId":"1","skuIds":["1"]},{"wareId":"2","skuIds":["10","13"]}]
        //1:订单微服务就要开始折单   父订单 折成多个子订单
        List<OrderInfo> orderInfoList = orderInfoService.orderSplit(orderId,wareSkuMap);
        List<Map> listMap = new ArrayList<>();
        //2:组合回调的数据
        orderInfoList.forEach(orderInfo -> {
            Map<String, Object> map = orderInfoService.initWareOrder(orderInfo);
            listMap.add(map);
        });
        return listMap;
    }
}
